package sky.dao.Impl;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import sky.dao.CityDAO;
import sky.domain.City;
import sky.domain.Country;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 19.05.13
 * Time: 17:28
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class CityDAOImpl implements CityDAO {

    @Autowired
    private SessionFactory sessionFactory;


    @Override
    public void addCity(City city) {
        Query query = sessionFactory.getCurrentSession().createQuery("from Country where name = ?");
        query.setParameter(0, city.getCountry().getName(), Hibernate.STRING);
        city.setCountry((Country) query.uniqueResult());
        sessionFactory.getCurrentSession().save(city);
    }

    @Override
    public void editCity(City city) {
        Query query = sessionFactory.getCurrentSession().createQuery("from Country where name = ?");
        query.setParameter(0, city.getCountry().getName(), Hibernate.STRING);
        city.setCountry((Country) query.uniqueResult());
        sessionFactory.getCurrentSession().update(city);
    }

    @Override
    public void removeCity(Integer id) {
        City city = (City) sessionFactory.getCurrentSession().load(City.class, id);
        if (null != city) {
            sessionFactory.getCurrentSession().delete(city);
        }
    }

    @Override
    public City getCityById(Integer id) {
        City city = (City) sessionFactory.getCurrentSession().get(City.class, id);
        Hibernate.initialize(city.getAirports());
        return city;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<City> cityList() {
        return sessionFactory.getCurrentSession().createQuery("from City").list();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<String> autocompleteList(String autocompleteString) {
        Query query = sessionFactory.getCurrentSession().createQuery("select name from City as city where city.name like  ''||?||'%'");
        query.setParameter(0, autocompleteString, Hibernate.STRING);
        query.setMaxResults(10);
        return query.list();
    }
}
